#include "Grid.h"
#include <nlohmann/json.hpp>
#include "Function.h"

using json = nlohmann::json;

Grid::Grid(const std::string& filename) {
    loadFromJson(filename);
    generateGrid();  // 生成网格
}

void Grid::loadFromJson(const std::string& filename) {
    // 读取 JSON 文件
    std::ifstream inputFile(filename);
    json config;
    inputFile >> config;

    // 解析输入参数
    dimension = config["grid"]["dimension"];
    n = config["grid"]["size"];
    xmin = config["grid"]["x_min"];
    xmax = config["grid"]["x_max"];
    if(dimension==2){
        ymin = config["grid"]["y_min"];
        ymax = config["grid"]["y_max"];
    }

    if (dimension == 1) {
        std::string exact_solution_1D_str = config["functions"]["exact_solution"];
        std::string source_term_1D_str = config["functions"]["source_term"];
        
        // 解析一维表达式
        exactSolution_1D = parseExpression_1D(exact_solution_1D_str);
        sourceTerm_1D = parseExpression_1D(source_term_1D_str);
        
        // 打印解析后的表达式（可以根据需要调整）
        /*std::cout << "Exact solution for 1D: " << exactSolution_1D(0) << std::endl;
        std::cout << "Source term for 1D: " << sourceTerm_1D(1) << std::endl;*/
    }
    else if (dimension == 2) {
        std::string exact_solution_2D_str = config["functions"]["exact_solution"];
        std::string source_term_2D_str = config["functions"]["source_term"];
        
        // 解析二维表达式
        exactSolution_2D = parseExpression_2D(exact_solution_2D_str);
        sourceTerm_2D = parseExpression_2D(source_term_2D_str);

        // 打印解析后的表达式（可以根据需要调整）
        /*std::cout << "Exact solution for 2D: " << exactSolution_2D(0, 0) << std::endl;
        std::cout << "Source term for 2D: " << sourceTerm_2D(1, 1) << std::endl;*/
    }
}

void Grid::generateGrid() {
    h = (xmax - xmin) / n;

    if(dimension==1){
        for (int i = 0; i < n+1; ++i) {
            grid_1D.push_back(xmin + i * h); 
        }
    }
    else if(dimension==2){
        for (int j = 0; j < n+1; ++j) {
            for(int i = 0; i < n+1; ++i){
                std::vector<double> row(xmin + i*h, ymin + j*h);
                grid_2D.push_back(row); 
            }
        }
    }
}